package com.example.sanguogameserver.config;

import com.example.sanguogameserver.consts.RedisKeyConst;
import com.example.sanguogameserver.service.ChatService;
import com.example.sanguogameserver.service.PlayerService;
import com.example.sanguogameserver.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ChatService chatService;

    @Autowired
    private PlayerService playerService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer redisMessageListenerContainer) {
        super(redisMessageListenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     *
     * @param message message must not be {@literal null}. 过期的key
     * @param pattern pattern matching the channel (if specified) - can be {@literal null}. 队列名称
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 拿到key
        String expiredKey = message.toString();
        log.info("监听Redis key过期，key：{}，channel：{}", expiredKey, new String(pattern));
        if (expiredKey.startsWith(RedisKeyConst.DeleteHash.name())) {
            String key = expiredKey.replace(RedisKeyConst.DeleteHash.name(), "");
            // 代表是聊天
            if (key.startsWith(RedisKeyConst.Chat.name())) {
                chatService.expirationKey(key);
            }
            if (key.startsWith(RedisKeyConst.Online.name())) {
                // 玩家设置离线
                String playerId = key.replace(RedisKeyConst.Online.name(), "");
                playerService.offline(Integer.parseInt(playerId));
            } else {
                // 其他删除
                Map<Object, Object> entries = redisUtil.entries(key);
                for (Object object : entries.keySet()) {
                    redisUtil.deleteHash(key, Integer.parseInt(object.toString()));
                }

            }
        }
    }
}
